// src/utils/geoLocation.js
import AMapLoader from '@amap/amap-jsapi-loader';

export default function getLocation() {
    return new Promise((resolve, reject) => {
        AMapLoader.load({
            key: '238d434aeec2fa650769eba0c23c1faa', // 替换为您的高德地图Key
            version: '2.0',
            plugins: ['AMap.Geolocation', 'AMap.Geocoder']
        })
            .then((AMap) => {
                const geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true, // 是否使用高精度定位，默认:true
                    timeout: 10000, // 超过10秒后停止定位，默认：无穷大
                    buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                    zoomToAccuracy: true, // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认:false
                });

                const geocoder = new AMap.Geocoder({
                    city: '010', // 默认城市为北京
                    radius: 1000
                });

                geolocation.getCurrentPosition((status, result) => {
                    if (status === 'complete') {
                        const position = result.position;
                        geocoder.getAddress([position.lng, position.lat], (status, result) => {
                            if (status === 'complete' && result.regeocode) {
                                // 只获取城市信息
                                resolve({
                                    lng: position.lng,
                                    lat: position.lat,
                                    city: result.regeocode.addressComponent.city
                                });
                            } else {
                                reject(new Error('根据经纬度查询地址失败'));
                            }
                        });
                    } else {
                        reject(new Error('定位失败，请检查定位权限'));
                    }
                });
            })
            .catch((error) => {
                reject(error);
            });
    });
}